﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class ScoreManager : MonoBehaviour {

	public static ScoreManager Instance;

	public Text scoreText;

	public Text levelText;

	public int score;

	private int baseScore = 20;
	private float scoreVary = 0.5f;

	private float speedIncrease = 0.01f;
	private float baseSpeed = 0.04f;
	private List<int> scoreLevel;
	int curLevel;

	public bool isGameOver = false;

	float timeCount = 0;

	public GameObject gameOverObj;
	public Text curScoreText;
	public Text bestScoreText;

	// Use this for initialization
	void Start () 
	{
		gameOverObj.SetActive(false);

		Instance = this;

		curLevel = 0;

		scoreLevel = new List<int>();
		for(int i = 0; i < 40; i++)
		{
			scoreLevel.Add((int)Mathf.Floor(baseScore * Mathf.Pow(1.5f, i)));
			//Debug.Log(scoreLevel[i].ToStscoreLevel[i].ToString());
		}
	}

	public void AddScore(int score)
	{
		this.score += score;

		if(curLevel < scoreLevel.Count && this.score > scoreLevel[curLevel])
		{
			curLevel++;

			// 设置更快的旋转速度
			RotateMove.rotateSpeed = (baseSpeed + curLevel * speedIncrease);
		}
	}
	
	// Update is called once per frame
	void Update () 
	{
		ScoreManager.Instance.scoreText.text = score.ToString();
		ScoreManager.Instance.levelText.text = "Lv " + (curLevel + 1);

		CheckGameOver();

		if(Input.GetKeyDown(KeyCode.I))
		{
			RestartGame();
		}
	}

	public void CheckGameOver()
	{
		if((CreateItem.Instance.deadIslandCount == 8 || (CreateItem.Instance.totalGenerateCount == 0 && CreateItem.Instance.objCount == 0)) && !isGameOver)
		{
			Debug.Log("======== Is game over =======");
			isGameOver = true;

			int bestScore;

			if(PlayerPrefs.HasKey("BestScore"))
			{
				bestScore = PlayerPrefs.GetInt("BestScore");
				if(score > bestScore)
				{
					Debug.Log("======== New Best Score =======");
					PlayerPrefs.SetInt("BestScore", score);
					bestScore = score;
				}
			}
			else
			{
				Debug.Log("======== New Best Score =======");
				bestScore = score;
				PlayerPrefs.SetInt("BestScore", score);
			}

			ShowGameOverPanel(score, bestScore);
			// TODO: 显示界面，最高分数

		}
	}

	public void ShowGameOverPanel(int curScore, int bestScore)
	{
		SoundManager.Instance.PlayLoseSound();
		curScoreText.text = curScore.ToString();
		bestScoreText.text = bestScore.ToString();
		gameOverObj.SetActive(true);
	}

	public void RestartGame()
	{
		RotateMove.rotateSpeed = (baseSpeed + 0 * speedIncrease);
		SceneManager.LoadScene("defaultScenes", LoadSceneMode.Single);
	}
}
